// CacheManager.h
#pragma once
#include <unordered_map>
#include <list>
#include <mutex>
#include <memory>
#include <vector>
#include <string>

struct CacheEntry {
    std::vector<uint8_t> data;
    size_t size;
    time_t lastAccess;
    bool dirty;  // 标记是否需要写回磁盘
};

class CacheManager {
public:
    explicit CacheManager(size_t maxSize = 512 * 1024 * 1024);  // 默认512MB缓存
    
    // 读取数据
    bool Get(const std::wstring& path, std::vector<uint8_t>& data, size_t offset, size_t length);
    
    // 写入数据
    bool Put(const std::wstring& path, const std::vector<uint8_t>& data, size_t offset);
    
    // 刷新缓存到磁盘
    void Flush();
    
    // 从缓存中移除
    void Remove(const std::wstring& path);
    
    // 获取缓存使用统计
    void GetStats(size_t& hitCount, size_t& missCount) const;

private:
    void EvictIfNeeded(size_t neededSize);
    void UpdateLRU(const std::wstring& path);
    
    std::unordered_map<std::wstring, CacheEntry> m_cache;
    std::list<std::wstring> m_lru;  // 最近最少使用队列
    
    const size_t m_maxSize;
    size_t m_currentSize;
    
    mutable std::mutex m_mutex;
    
    // 统计信息
    size_t m_hitCount;
    size_t m_missCount;
};